//
//  PrinterHelper.m
//  Honda
//
//  Created by HeninHoo on 13-4-25.
//  Copyright (c) 2013年 HeninHoo. All rights reserved.
//

#import "PrinterHelper.h"

@implementation PrinterHelper

- (id)initWithPrintView:(UIView *)printView
{
    if ( self = [super init] )
    {
        _printView = printView;
        
        [self print];
    }
    
    return self;
}


- (void)print{

    UIPrintInteractionController *print = [UIPrintInteractionController sharedPrintController];

    if(!print){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Print Unavailable!" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }

    CGSize pageSize = print.printPaper.paperSize;
    pageSize = CGSizeMake(print.printFormatter.printPageRenderer.printableRect.size.width, print.printFormatter.printPageRenderer.printableRect.size.height);

    //截屏
    UIGraphicsBeginImageContext(_printView.bounds.size);
    //截webview
//        UIGraphicsBeginImageContext(webview.frame.size);

    [_printView.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image= UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

//        UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);

    NSData *screenImgData = UIImageJPEGRepresentation(image, 1);
    

//    UIImage *resultImage;
//    {//webview
//        int webViewHeight = [[webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] integerValue];
//        int scrollByY = webview.frame.size.height;
//        int imageName = 0;
//
//        [webview stringByEvaluatingJavaScriptFromString:@"window.scrollTo(0,0);"];
//
//        NSMutableArray* images = [[NSMutableArray alloc] init];
//
//        CGRect screenRect = webview.frame;
//        double currentWebViewHeight = webViewHeight;
//        while (currentWebViewHeight > 0)
//        {
//            imageName ++;
//
//            UIGraphicsBeginImageContext(screenRect.size);
//            CGContextRef ctx = UIGraphicsGetCurrentContext();
//            [[UIColor blackColor] set];
//            CGContextFillRect(ctx, screenRect);
//
//            [webview.layer renderInContext:ctx];
//
//            UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//            UIGraphicsEndImageContext();
//
//            if(currentWebViewHeight < scrollByY)
//            {
//                CGRect lastImageRect = CGRectMake(0, scrollByY - currentWebViewHeight, webview.frame.size.width, currentWebViewHeight);
//                CGImageRef imageRef = CGImageCreateWithImageInRect([newImage CGImage], lastImageRect);
//
//                newImage = [UIImage imageWithCGImage:imageRef];
//                CGImageRelease(imageRef);
//            }
//            [images addObject:newImage];
//
//            [webview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollBy(0,%d);", scrollByY]];
//            currentWebViewHeight -= scrollByY;
//        }
//
//        [webview stringByEvaluatingJavaScriptFromString:@"window.scrollTo(0,0);"];
//
////        UIImage *resultImage;
//
//        if(images.count > 1) {
//            //join all images together..
//            CGSize sz;
//            for(int i=0;i<images.count;i++) {
//
//                sz.width = MAX(sz.width, ((UIImage*)[images objectAtIndex:i]).size.width );
//                sz.height += ((UIImage*)[images objectAtIndex:i]).size.height;
//            }
//
//            UIGraphicsBeginImageContext(sz);
//            CGContextRef ctx = UIGraphicsGetCurrentContext();
//            [[UIColor blackColor] set];
//            CGContextFillRect(ctx, screenRect);
//
//            int y=0;
//            for(int i=0;i<images.count;i++) {
//
//                UIImage* img = [images objectAtIndex:i];
//                [img drawAtPoint:CGPointMake(0,y)];
//                y += img.size.height;
//            }
//
//            resultImage = UIGraphicsGetImageFromCurrentImageContext();
//            UIGraphicsEndImageContext();
//        } else {
//
//            resultImage = [images objectAtIndex:0];
//        }
//    }

    //NSData *finalImageData = UIImageJPEGRepresentation([UIImage imageNamed:@"111.jpg"], 0.1f);
//    NSData *finalImageData = UIImageJPEGRepresentation(resultImage, 0.1f);


    //    print.delegate = self;
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;
    //    printInfo.jobName = [[(PageView *)[self view] representedPage] title];
    printInfo.jobName = @"111";
    printInfo.duplex = UIPrintInfoDuplexLongEdge;
    print.printInfo = printInfo;
    print.showsPageRange = YES;
    print.printingItem = screenImgData;
    UIViewPrintFormatter *viewFormatter = [_printView viewPrintFormatter];
    viewFormatter.startPage = 0;

    print.printFormatter = viewFormatter;

    UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printInteractionController, BOOL completed, NSError *error) {
        if(!completed && error){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Print Unavailable!" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        }
    };

    [print presentAnimated:YES completionHandler:completionHandler];
}


@end
